package com.hd.pzhwlxt.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hd.pzhwlxt.pojo.Address;
import com.hd.pzhwlxt.service.AddressService;
import com.hd.pzhwlxt.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @create: 2022-09-21 14:06
 * @author: 怀念天空
 * @Description: 地址模块
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;


    @GetMapping("/get")
    public Response<Object> getAllAddress(@RequestParam(value = "pageNum",required = false) Integer pageNum, @RequestParam(value = "pageSize",required = false) Integer pageSize){
        if (pageNum == null || pageSize == null){
            List<Address> result = addressService.getAllAddress();
            if (result !=null){
                return Response.createSuccessResponse("查询成功",result);
            }
            return Response.createErrorResponse("查询失败");
        }
        Page<Address> result = addressService.getAllAddressPage(pageNum, pageSize);
        if (result !=null){
            return Response.createSuccessResponse("查询成功",result);
        }
        return Response.createErrorResponse("查询失败");
    }

    //批量删除
    @DeleteMapping("/del/{ids}")
    public Response<String> deleteMoreAddress(@PathVariable Integer[] ids){
        boolean remove = addressService.removeBatchByIds(Arrays.asList(ids));
        if (remove){
            return Response.createSuccessResponse("删除成功");
        }
        return Response.createErrorResponse("删除失败");
    }

    @PostMapping("/add")
    public Response<String> addAddress(@RequestBody Address address){
        String[] split = address.getAddress().split("/");
        address.setProvice(split[0]);
        address.setCities(split[1]);
        address.setArea(split[2]);
        boolean save = addressService.save(address);
        if (save){
            return Response.createSuccessResponse("添加成功");
        }
        return Response.createErrorResponse("添加失败");
    }

    @PutMapping("/update")
    public Response<String> updateAddress(@RequestBody Address address){
        String[] split = address.getAddress().split("/");
        address.setProvice(split[0]);
        address.setCities(split[1]);
        address.setArea(split[2]);
        boolean update = addressService.updateById(address);
        if (update){
            return Response.createSuccessResponse("修改成功");
        }
        return Response.createErrorResponse("修改失败");
    }
}
